package com.navi.loaddata.job;

import com.navi.loaddata.core.job.QuartzManage;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.mysqlEntity.EtlConfDMapper;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import com.navi.loaddata.loadService.IEtlConfServices;
import com.navi.loaddata.loadService.impl.edaDifference.LoadEdaDiffService;
import com.navi.loaddata.loadService.impl.edaDifference.LoadEdaHisDiffService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

//import com.navi.loaddata.loadService.impl.measureData.LoadMeasureDataService;

/**
 * @author jay
 */
@Service
//@DisallowConcurrentExecution//禁止并发
public class LoadHisDifference implements Job {
    private static final Logger logger = LoggerFactory.getLogger(LoadHisDifference.class);
    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());

    @Autowired
    private QuartzManage quartzManage;

    @Autowired
    private LoadEdaHisDiffService loadEdaDiffService;

    @Autowired
    private IEtlConfServices etlConfServices;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        EtlConfD etlConfD = (EtlConfD) jobDataMap.get("etlConf");
        etlConfD = etlConfServices.getNewConf(etlConfD);
        if (null == etlConfD) {
            logger.error("找不到该JOB。");
            return;
        }

        if ("N".equals(etlConfD.getRunFlg())) {
            etlConfD = etlConfServices.beginJob(etlConfD);
            if (StringUtils.isEmpty(etlConfD.getQueryMinute())) {
                return;
            }
            startETL(etlConfD);
        } else {
            logger.info("Job {}-{} is running.", etlConfD.getJobGroupName(), quartzManage.getRealJobName(etlConfD));
        }
    }

    private void startETL(EtlConfD etlConfD) {
        //获取站点
        List<String> opes = new ArrayList<>();
        if (!StringUtils.isEmpty(etlConfD.getOpe())) {
            opes.add(etlConfD.getOpe());
        } else if (!StringUtils.isEmpty(etlConfD.getOpes())) {
            String[] opeIds = etlConfD.getOpes().split(",");
            for (String ope : opeIds) {
                opes.add(ope);
            }
        }else{
            opes.add(null);
        }

        EtlConfDModel etlConfDModel= EtlConfDMapper.INSTANCE.etlConfDToModel(etlConfD);
        int okCnt = 0;
        int errCnt = 0;

        //循环STEP
        for(String ope:opes){
            etlConfDModel.setOpe(ope);
            try {
                String[] resMsg=new String[3];//okCnt,errCnt,errMsg
                resMsg = loadEdaDiffService.loadEdaDiffMain(etlConfDModel);

                EtlConfDModel etlConfDByOpe= etlConfServices.endJobOfModel(etlConfD);
                if (null == etlConfDByOpe) return;
                etlConfDByOpe.setOpe(ope);
                etlConfDByOpe.setCountSize(ProcessUtil.getStr2Cnt(resMsg[0]));
                etlConfDByOpe.setErrorCnt(ProcessUtil.getStr2Cnt(resMsg[1]));
                etlConfServices.addHisOfModel(etlConfDByOpe, resMsg[2]);

                okCnt=okCnt+ ProcessUtil.getStr2Cnt(resMsg[0]);
                errCnt=errCnt+ ProcessUtil.getStr2Cnt(resMsg[1]);


            } catch (Exception e) {
                logger.error(LoggerUtil.stackTraceToString(e));

                logger.info("Job {} [{}]-[{}] OPE={} FAIL TO SYNCHRONIZE.", etlConfD.getProjectName() + etlConfD.getJobGroupName() + etlConfD.getJobName(), etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp(),ope);
                EtlConfDModel etlConfDByOpe= etlConfServices.endJobOfModel(etlConfD);
                if (null == etlConfDByOpe) return;
                etlConfDByOpe.setOpe(ope);
                etlConfDByOpe.setCountSize(0);
                etlConfDByOpe.setErrorCnt(-1);

                etlConfServices.addHisOfModel(etlConfDByOpe, "ope="+ope+","+e.getMessage());

                if(null!=e.getMessage()&&(e.getMessage().contains("Unable to acquire JDBC Connection")||e.getMessage().contains("ORA-01683")||e.getMessage().contains("ORA-01688"))){//无法连接,SLEEP
                    etlConfD = etlConfServices.getNewConf(etlConfD);
                    etlConfD.setValidFlg("N");
                    etlConfD.setRunFlg("N");
                    etlConfServices.saveReloadJob(etlConfD);
                    try{
                        Thread thread = Thread.currentThread();
                        thread.sleep(60000);//暂停60秒后程序继续执行
                    }catch (InterruptedException ex) {
                        logger.error(LoggerUtil.stackTraceToString(ex));
                    }
                    etlConfD = etlConfServices.getNewConf(etlConfD);
                    etlConfD.setValidFlg("Y");
                    etlConfServices.saveReloadJob(etlConfD);
                    return;
                }
            }
        }
        etlConfD.setCountSize(okCnt);
        etlConfD.setErrorCnt(errCnt);
        etlConfServices.endJob(etlConfD);
//        etlConfServices.addHis(etlConfD, null);

    }
}
